<template>
  <div>
    <div ref="toolbarContainer" style="border-bottom: 1px solid #ccc;"></div>
    <div ref="editorContainer" style="min-height: 300px; border: 1px solid #ccc;"></div>
  </div>
</template>

<script>
import { onMounted, onBeforeUnmount, ref, watch } from 'vue';
import { createEditor, createToolbar } from '@wangeditor/editor';
import '@wangeditor/editor/dist/css/style.css';
import { ElMessage } from 'element-plus';

export default {
  props: {
    modelValue: {
      type: String,
      default: ''
    }
  },
  emits: ['update:modelValue'],
  setup(props, { emit }) {
    const editor = ref(null);
    const toolbar = ref(null);
    const editorContainer = ref(null);
    const toolbarContainer = ref(null);

    onMounted(() => {
      editor.value = createEditor({
        selector: editorContainer.value,
        mode: 'default',
        config: {
          placeholder: '请输入内容...',
          onChange: (editorInstance) => {
            const html = editorInstance.getHtml();
            emit('update:modelValue', html);
          },
          MENU_CONF: {
            uploadImage: {
              server: 'http://localhost:8080/files/wang/upload',
              fieldName: 'file',
              maxFileSize: 10 * 1024 * 1024, // 10MB
              maxNumberOfFiles: 10,
              allowedFileTypes: ['image/*'],
              metaWithUrl: true,
              withCredentials: false,
              timeout: 5 * 1000, // 5s
              customInsert: (insertFn, result) => {
                console.log('WangEditor customInsert called with result:', result);
                console.log('Type of result:', typeof result);
                
                // 如果 result 是函数，说明是 WangEditor 内部调用，直接返回
                if (typeof result === 'function') {
                  console.log('Result is a function, likely internal call, returning.');
                  return;
                }

                // 尝试解析 JSON 字符串，以防后端返回的是字符串化的 JSON
                let parsedResult = result;
                if (typeof result === 'string') {
                  try {
                    parsedResult = JSON.parse(result);
                    console.log('Parsed string result:', parsedResult);
                  } catch (e) {
                    console.error('Failed to parse result string as JSON:', e);
                    // 如果解析失败，仍然使用原始 result
                    parsedResult = result;
                  }
                }

                // 如果 result 是对象且包含 data 数组
                if (parsedResult && typeof parsedResult === 'object' && Array.isArray(parsedResult.data) && parsedResult.data.length > 0) {
                  const url = parsedResult.data[0].url;
                  if (url) {
                    // 使用完整的图片标签格式
                    const imgHtml = `<img src="${url}" alt="图片" style="max-width: 100%;"/>`;
                    if (typeof insertFn === 'function') {
                       insertFn(imgHtml);
                       console.log('图片插入成功:', url);
                    } else {
                       console.error('insertFn is not a function:', insertFn);
                       ElMessage.error('图片插入失败，请重试');
                    }
                  } else {
                     console.error('图片上传成功但 URL 无效:', parsedResult);
                     ElMessage.error('图片上传成功但 URL 无效');
                  }
                } else {
                  console.error('图片上传失败，返回数据格式不正确或缺少 data 数组:', parsedResult);
                  ElMessage.error('图片上传失败，请重试');
                }
              },
              onError(file, err, res) {
                console.error('图片上传失败:', file, err, res);
                ElMessage.error('图片上传失败: ' + (err.message || '未知错误'));
              },
              onBeforeUpload(file) {
                console.log('准备上传文件:', file);
                if (file.size > 10 * 1024 * 1024) {
                  ElMessage.error('文件大小不能超过 10MB');
                  return false;
                }
                return true;
              }
            }
          }
        }
      });

      toolbar.value = createToolbar({
        editor: editor.value,
        selector: toolbarContainer.value,
        mode: 'default',
        config: {}
      });

      // 设置初始内容
      editor.value.setHtml(props.modelValue);
    });

    watch(() => props.modelValue, (newVal) => {
      if (editor.value && editor.value.getHtml() !== newVal) {
        editor.value.setHtml(newVal);
      }
    });

    onBeforeUnmount(() => {
      if (toolbar.value) toolbar.value.destroy();
      if (editor.value) editor.value.destroy();
    });

    return {
      editorContainer,
      toolbarContainer
    };
  }
};
</script>